class_name Boar
extends Enemy

enum State{
	IDLE,
	WALK,
	RUN,
	HURT,
	DYING,
}

@onready var wall_checker: RayCast2D = $Graphics/WallChecker
@onready var floor_checker: RayCast2D = $Graphics/FloorChecker
@onready var player_checker: RayCast2D = $Graphics/PlayerChecker
@onready var clam_down_timer: Timer = $ClamDownTimer

var pending_damage_queue: Array[Damage]

func can_see_player() -> bool:
	if not player_checker.is_colliding():
		return false
	return player_checker.get_collider() is Player

func get_next_state(state: State) -> State:
	#var pending_damage := pending_damage_queue.pop_front() as Damage
	if stats.health <= 0:
		return State.DYING
	if !pending_damage_queue.is_empty():
		return State.HURT
	match state:
		State.IDLE:
			if can_see_player():
				return State.RUN
			if state_machine.state_time > 2:
				return State.WALK
		State.WALK:
			if wall_checker.is_colliding() or not floor_checker.is_colliding():
				return State.IDLE
		State.RUN:
			if not can_see_player() and clam_down_timer.is_stopped():
				return State.WALK
		State.HURT:
			if not animation_player.is_playing():
				return State.RUN
		
	return state

func transition_state(from: State, to: State) -> void:
	#print("[%s] %s => %s" % [
		#Engine.get_physics_frames(),
		#State.keys()[from] if from != -1 else "<START>",
		#State.keys()[to],
	#])
	match to:
		State.IDLE:
			animation_player.play("idle")
			if wall_checker.is_colliding():
				direction *= -1
		State.WALK:
			animation_player.play("walk")
			if not floor_checker.is_colliding():
				direction *= -1
				# 强制更新缓存中的值
				floor_checker.force_raycast_update()
		State.RUN:
			animation_player.play("run")
		State.HURT:
			animation_player.play("hit")
			var pending_damage := pending_damage_queue.pop_front() as Damage
			stats.health -= pending_damage.amount
			
		State.DYING:
			animation_player.play("death")
	
func tick_physics(state: State, delta: float) ->void:
	match state:
		State.IDLE:
			move(0.0, delta)
		State.WALK:
			move(max_speed/3, delta)
		State.RUN:
			if wall_checker.is_colliding() or not floor_checker.is_colliding():
				direction *= -1
			move(max_speed, delta)
			if can_see_player():
				clam_down_timer.start()


func _on_hurtbox_hurt(hitbox: Hitbox) -> void:
	var pending_damage = Damage.new()
	var player = hitbox.owner as Player
	pending_damage.amount = player.get_currery_attack_power()
	pending_damage.source = hitbox.owner
	pending_damage_queue.append(pending_damage)
	#var player : Player = hixbox.owner
	#print(player.get_currery_attack_power())
	#stats.health -= 1
	#if stats.health <= 0:
		#queue_free()
